﻿using System.Text;

namespace shelltwitlib
{
	public class Util
	{
		const string UPDATE_STATUS = "http://twitter.com/statuses/update.xml";

		//Basic auth is deprecated
		//public static string UpdateStatus(string status)
		//{
		//    if (status.Length > 140)
		//        throw new Exception("status must be at most 140 characters long");

		//    TwitterUser user = TwitterUser.LoadCredentials();
		//    byte[] bytes = GetUTF8EncodingBytes(string.Format("status={0}", status));

		//    HttpWebRequest request = GetUpdateStatusRequest(bytes, user.GetUrlData());
		//    using (Stream reqStream = request.GetRequestStream())
		//        reqStream.Write(bytes, 0, bytes.Length);

		//    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

		//    return response.StatusDescription;
		//}

		//public static string UpdateStatusOAuth(string status)
		//{
		//    if (status.Length > 140)
		//        throw new Exception("status must be at most 140 characters long");

		//    TwitterUser user = TwitterUser.LoadCredentials();
		//    string encodedStatus = EncodeString(status);
		//    HttpWebRequest req = shelltwitlib.Status.Update.GetUpdateStatusRequest(user.OAuthToken, user.OAuthTokenSecret, encodedStatus);

		//    byte[] bytes = GetUTF8EncodingBytes(string.Format("status={0}", encodedStatus));

		//    req.ContentLength = bytes.Length;
		//    using (Stream str = req.GetRequestStream())
		//        str.Write(bytes, 0, bytes.Length);

		//    HttpWebResponse response = (HttpWebResponse)req.GetResponse();

		//    if (response.StatusCode != HttpStatusCode.OK)
		//        return response.StatusDescription;

		//    string data = string.Empty;
		//    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
		//        data = reader.ReadToEnd();

		//    XmlDocument doc = new XmlDocument();
		//    try
		//    {
		//        doc.LoadXml(data);
		//    }
		//    catch 
		//    {
		//        doc = null;
		//    }

		//    if (doc == null)
		//        return data;
		//    else
		//        return response.StatusDescription;
		//}

		// Basic Auth is deprecated
		//static HttpWebRequest GetUpdateStatusRequest(byte[] data, string user)
		//{
		//    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UPDATE_STATUS);
		//    request.Method = "POST";
		//    request.Headers.Add("Authorization", "Basic " + user);
		//    request.ContentType = "application/x-www-form-urlencoded";
		//    request.ServicePoint.Expect100Continue = false;
		//    request.ContentLength = data.Length;
		//    request.UserAgent = "@sebagomez shelltwit";

		//    return request;
		//}

		static string UNRESERVED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

		//http://en.wikipedia.org/wiki/Percent-encoding
		//http://www.w3schools.com/tags/ref_urlencode.asp see 'Try It Yourself' to see if this function is encoding well
		//This should be encoded according to RFC3986 http://tools.ietf.org/html/rfc3986
		//I could not find any native .net function to achieve this
		/// <summary>
		/// Encodes a string according to RFC 3986
		/// </summary>
		/// <param name="value">string to encode</param>
		/// <returns></returns>
		public static string EncodeString(string value)
		{
			StringBuilder sb = new StringBuilder();
			foreach (char c in value)
			{
				if (UNRESERVED_CHARS.IndexOf(c) != -1)
					sb.Append(c);
				else
				{
					byte[] encoded = Encoding.UTF8.GetBytes(new char[] { c });
					for (int i = 0; i < encoded.Length; i++)
					{
						sb.Append('%');
						sb.Append(encoded[i].ToString("X2"));
					}
				}
			}
			return sb.ToString();
		}

		public static byte[] GetUTF8EncodingBytes(string value)
		{
			return Encoding.UTF8.GetBytes(value);
		}
	}
}
